package web.java.h_generatedKeys;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

import web.java.z_JDBCUtil.DBUtil;

public class Demo01_GeneratedKeys {
	/**
	 * 获取每次执行插入数据之后的自增长的键值
	 * */
	//全局变量
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet result;
	@Test
	public void test1(){
		conn=DBUtil.connection();
		String sql="insert into user (name,permission_id,deposit) values('刘天成',2,2000)";
		try{
			pstmt=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			pstmt.executeUpdate();
			//自增长的键值在执行update操作之后可以获取到
			//自增长的键值不一定是一个，有可能是多个
			result=pstmt.getGeneratedKeys();
			if(result.next()){
				System.out.println(result.getInt(1));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			DBUtil.closeConn(conn, pstmt, result);
		}
	}
}
